package io.renren.modules.backstage.service.impl;

import io.renren.common.exception.StatusCode;
import io.renren.common.utils.Result;
import io.renren.modules.backstage.dao.CreditDao;
import io.renren.modules.backstage.dao.UsersDao;
import io.renren.modules.backstage.entity.BankCard;
import io.renren.modules.backstage.entity.CreditEntity;
import io.renren.modules.backstage.entity.UsersEntity;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.backstage.dao.BankcardDao;
import io.renren.modules.backstage.entity.BankcardEntity;
import io.renren.modules.backstage.service.BankcardService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("bankcardService")
public class BankcardServiceImpl extends ServiceImpl<BankcardDao, BankcardEntity> implements BankcardService {

    @Resource
    private BankcardDao bankcardDao;

    @Resource
    private UsersDao usersDao;

    @Resource
    private CreditDao creditDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BankcardEntity> page = this.page(
                new Query<BankcardEntity>().getPage(params),
                new QueryWrapper<BankcardEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public Result verifyCard(BankCard bankCard) {
        BankcardEntity bankcardEntity = new BankcardEntity(0, bankCard.getCardNumber(), bankCard.getPhoneNumber(), bankCard.getName(), bankCard.getIdNumber());
        bankcardDao.insertBankCard(bankcardEntity);
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",bankCard.getUserId());
        UsersEntity user = usersDao.selectOne(wrapper);
        QueryWrapper<CreditEntity> creditWrapper = new QueryWrapper<>();
        creditWrapper.eq("real_name",bankCard.getName());
        CreditEntity creditEntity = creditDao.selectOne(creditWrapper);
        if(null != creditEntity){
            user.setCreditScore(creditEntity.getCreditPoints());
        }
        user.setCardId(bankcardEntity.getCardId());
        user.setIfCertificated(1);
        user.setIdentityId(bankCard.getIdNumber());
        usersDao.update(user,wrapper);
        return new Result(StatusCode.OK,"绑卡成功",true);
    }

}